import { useRouter } from "next/navigation";
import { QueryClient, useMutation } from "@tanstack/react-query";
import { useForm } from "react-hook-form";
import { AuthService } from "@/shared/api/api.auth";
import { Mesh } from "three";
import { useEffect, useRef, useState } from "react";
import { IModel, IModelDto } from "@/shared/interfaces";
import { ModelServise } from "@/shared/api/api.model";
import { Router } from "next/router";

export function useSetupModel(names: string[], modelName: string, modelFilePath: string) {
    const ModelDataRef = useRef<IModelDto>({
        name: modelName,
        modelFilePath: modelFilePath,
        meshes: []
    })
    const [index, setIndex] = useState(0)
    const router = useRouter();
    const { register, handleSubmit } = useForm<{
        interactive: boolean;
        name: string;
        description: string;
    }>();


    const onSubmit = (
        data: {
            interactive: boolean;
            name: string;
            description: string;
        }
    ) => {
        console.log(index)
        if (index < names.length-1) {
            ModelDataRef.current.meshes.push({
                originalMeshName: names[index],
                interactive: data.interactive,
                name: data.name,
                description: data.description
            })
        }
        if (index >= names.length-1) {
            console.log(ModelDataRef.current)
            createModelMutation.mutate(ModelDataRef.current)
        }
        else {
            setIndex(i => i + 1)
        }
    }

    const queryClient = new QueryClient

    const createModelMutation = useMutation(
        {
            mutationFn: ModelServise.create,
        }, queryClient
    );



    return {
        index,
        register,
        handleSubmit: handleSubmit((data) => { onSubmit(data) }),
        isSuccess: createModelMutation.isSuccess,
        response: createModelMutation.data,
        isError: createModelMutation.isError,
        errorMessage: createModelMutation.error,
        isPending: createModelMutation.isPending
    };
}